package com.student.wym.controller;

import com.student.wym.po.Teacher;
import com.student.wym.service.ITeacherService;
import com.student.wym.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

@Controller
public class LoginController {

    @Autowired
    private ITeacherService teacherService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String goPage() {
        return "login";
    }

    @RequestMapping(value = "/loginOut", method = RequestMethod.GET)
    public String loginOut(HttpServletRequest request) {
        request.getSession().invalidate();
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult login(HttpServletRequest request, String username, String password) {
        Teacher teacher = teacherService.findOne(username);
        if (teacher == null) {
            return new JSONResult(1, "用户不存在!");
        } else {
            if (!teacher.getPassword().equals(password)) {
                return new JSONResult(1, "密码错误!");
            } else {
                teacher.setLastLoginTime(new Date());//上次登录时间
                try {
                    teacher.setLastLoginIp(InetAddress.getLocalHost().getHostAddress());//ip
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                teacherService.loginInfo(teacher);
                request.getSession().setAttribute("TEACHER_IN_SESSION", teacher);
                return new JSONResult(0, "登录中...");
            }
        }
    }

    @RequestMapping("/main")
    public String main() {
        return "main";
    }

}
